//
//  ZZOAuthViewController.swift
//  sina
//
//  Created by 张鹏 on 16/5/23.
//  Copyright © 2016年 ZP. All rights reserved.
//

import UIKit
import SVProgressHUD

        //遵守UIWebViewDelegate
class ZZOAuthViewController: UIViewController ,UIWebViewDelegate{
    
        //设置一个webView
     let webView = UIWebView()
    
    override func loadView() {
        //用webView替换view
        view = webView
        
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setNavBar()
        loadOAuthPage()
    }
    
    //打开授权页面
    func loadOAuthPage() {
    
        //获取URL路径
        //http://open.weibo.com/apps/3440263826/info/basic
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        //获取url
        let url = NSURL(string: urlString)
    
        //发送网络请求
        let req = NSURLRequest(URL: url!)
        
        webView.loadRequest(req)
    
    
    }
    
}

    extension ZZOAuthViewController {
    //设置nav导航条按钮
      private func setNavBar() {
            navigationItem.leftBarButtonItem = UIBarButtonItem( title: "返回", target: self, action: #selector(ZZOAuthViewController.close))
        print(title)
        
            navigationItem.rightBarButtonItem = UIBarButtonItem( title: "测试登录", target: self, action: #selector(ZZOAuthViewController.textAccount))
        }

        
    //返回按钮的点击事件
    @objc private func close() {
    
    dismissViewControllerAnimated(true, completion: nil)
    }

    //静态注入
    @objc private func textAccount() {

        let jsString = "document.getElementById('userId').value = '578530825@qq.com', document.getElementById('passwd').value = 'a15638716113' "
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
}

}

    extension ZZOAuthViewController  {

    func webViewDidStartLoad(webView: UIWebView) {
        
        //显示用户等待指示器
        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        
        //隐藏用户等待指示器
        SVProgressHUD.dismiss()
        
    }
        
        //授权成功后,就会回掉新的界面,  在回掉过程中就包含code值\
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            //返回值是一个bool值,返回true表示回掉新的界面
            
            //1. 获取urlString的绝对路径
            let urlString = request.URL?.absoluteString ?? ""
            //2. 获取截取成功之后的code字符串
            let successFlag = "code="
            
            //判断逻辑 : 如果字符串中包含code值  contain :包含
            if urlString.containsString(successFlag) {
                //获取successFlag的位置
                //在获取successFlag的位置的时候强制解包.表示一定确定能够获得code值
                let rang = urlString.rangeOfString(successFlag)!
                //获取successFlag最后一个index的位置
                let code = urlString.substringFromIndex(rang.endIndex)
                
                //获取code成功后,应使用code码请求token(用户访问令牌)
//                loadAccessToken(code)
//                
//              ZZUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code)
//                
//                 return false
                ZZUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
                    
                    if !isSuccess {
                    SVProgressHUD.showErrorWithStatus(noWIFI)
                        return
                    }
                    //成功
                    SVProgressHUD.showSuccessWithStatus("请求成功")
                    print(isSuccess)
                })
                
                return false
            }
            
            
       
            return true
        }
}
        //以下代码封装到视图模型中
//        //获取code值之后,根据code值 获取token值
//        func loadAccessToken (code : String) {
//            //获取网络请求
//            let urlString = "https://api.weibo.com/oauth2/access_token"
//            let parameters = ["client_id":client_id, "client_secret":client_secret, "grant_type":"authorization_code", "code":code, "redirect_uri":redirect_uri]
//            //发送网络请求
//            ZZNetworkTools.sharedTools.request(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
//                
//                print(responseObject, error)
//                //请求失败
//                if error != nil {
//                    SVProgressHUD.showSuccessWithStatus(noWIFI)
//                    return
//                }
//                //请求成功
//                self.loadUserInfo(responseObject)
//                print("请求成功")
//            }
//        }
//        
//        //token值请求成功
//        private func loadUserInfo(responseObject : AnyObject?) {
//            //强转字典类型
//            guard let result = responseObject as? [String : AnyObject] else {
//                
//                SVProgressHUD.showSuccessWithStatus(noWIFI)
//                return
//            }
//            //字典中不可以添加nil,  token uid 是可选项, 所以要强制解包
//            let token = result["access_token" ]!
//            let uid = result["uid"]!
//            
//            let urlString = "https://api.weibo.com/2/users/show.json"
//            
//            let parameters = ["access_token":token, "uid":uid]
//            
//            //发送网络请求
//            ZZNetworkTools.sharedTools.request(.GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
//                
//                //请求失败
//                if error != nil {
//                    SVProgressHUD.showSuccessWithStatus(noWIFI)
//                    return
//                }
//                print("---------打印token值-----------")
//                print(responseObject)
//                
//                //请求成功
//                guard var dict = responseObject as? [String : AnyObject] else {
//                    
//                    SVProgressHUD.showSuccessWithStatus(noWIFI)
//                    return
//                }
//                
//                //遍历两个字典的用户信息
//                //合并两个字典,把数据保存到本地
//                //key 和 value 的值不会发生改变
//                for (key, value) in result {
//                    dict[key] = value
//                    
//                }
//                
//                
//                let user = ZZUserAccount(dict: dict)
//                print("user.................................")
//                print(user)
//                //将模型对象转化为字典
//                let key = ["access_token", "expires_in", "uid", "name", "avatar_large"]
//                let userInfo = user.dictionaryWithValuesForKeys(key)
//                print(userInfo)
//                
//                //设置偏好设置,保存字典数据
//                //standardUserDefaults() :用来实例化NSUserDefaults
//                let userDefaults = NSUserDefaults.standardUserDefaults()
//                
//                //不能够向偏好设置中保存nil
//                userDefaults.setObject(userInfo, forKey: userInfoKey)
//                
//                //同步 syn
//                userDefaults.synchronize()
//                
//                
//                //打印偏好设置保存路径
//                print(NSHomeDirectory())
//                
//                
//                
//            }
//        }



